package name.vaccari.matteo.tai.phonedirectory.web;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class BaseViewTestCase {

	protected String getNodeContent(Document doc, String xpath)
			throws XPathExpressionException {
		NodeList nodes = getNodeList(doc, xpath);
		assertEquals("expected exactly 1 node at xpath " + xpath, 1, nodes
				.getLength());
		return nodes.item(0).getTextContent();
	}

	protected NodeList getNodeList(Document doc, String xpath)
			throws XPathExpressionException {
		// see http://www.ibm.com/developerworks/library/x-javaxpathapi.html
		XPathFactory factory = XPathFactory.newInstance();
		XPath xp = factory.newXPath();
		return (NodeList) xp.evaluate(xpath, doc, XPathConstants.NODESET);
	}

	protected Document documentFromString(String string) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		factory.setNamespaceAware(true);
		return factory.newDocumentBuilder().parse(
				new ByteArrayInputStream(string.getBytes()));
	}

}
